package com.senjoeson.wanandroid.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.senjoeson.wanandroid.R;
import com.senjoeson.wanandroid.api.BaseResponse;
import com.senjoeson.wanandroid.api.RetrofitManager;
import com.senjoeson.wanandroid.base.App;
import com.senjoeson.wanandroid.base.BaseFragment;
import com.senjoeson.wanandroid.model.ArticleData;
import com.senjoeson.wanandroid.model.BannerData;
import com.senjoeson.wanandroid.ui.Html5Activity;
import com.senjoeson.wanandroid.utils.ALog;
import com.senjoeson.wanandroid.utils.TimeUtils;
import com.senjoeson.wanandroid.wrapper.GlideImageLoader;
import com.senjoeson.wanandroid.wrapper.MyBaseListObserver;
import com.senjoeson.wanandroid.wrapper.RecyclerViewDivider;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author senjoeson
 * @date 2018/4/1
 */
public class HomeFragment extends BaseFragment {


    ArrayList<String> images = new ArrayList<>();
    ArrayList<String> descs = new ArrayList<>();
    public List<BannerData> mBannerData;

    Banner mBanner;
    @BindView(R.id.recylerview)
    RecyclerView mRecylerview;
    @BindView(R.id.swiperefreshlayout)
    SwipeRefreshLayout mSwiperefreshlayout;
    public BaseQuickAdapter<ArticleData.DatasBean, BaseViewHolder> mBaseQuickAdapter;


    private int startPage = 0;
    public ArticleData mArticleData;


    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_home;
    }

    @Override
    protected void onInitView() {


        mSwiperefreshlayout.setEnabled(true);
        mRecylerview.setLayoutManager(new LinearLayoutManager(getContext()));
        mBaseQuickAdapter = new BaseQuickAdapter<ArticleData.DatasBean, BaseViewHolder>(R.layout.fragment_home_item) {
            @Override
            protected void convert(BaseViewHolder helper, ArticleData.DatasBean item) {
                helper.setText(R.id.author, item.getAuthor());
                helper.setText(R.id.title, item.getTitle());
                helper.setText(R.id.chapterName, item.getSuperChapterName()+"/"+item.getChapterName());
                long publishTime = item.getPublishTime();
                helper.setText(R.id.publishTime, TimeUtils.parseTime(publishTime));

            }
        };
        mBanner = new Banner(App.getContext());
        mBanner.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 320));
        mBaseQuickAdapter.addHeaderView(mBanner);
        mRecylerview.setAdapter(mBaseQuickAdapter);
        mBaseQuickAdapter.openLoadAnimation();
        mRecylerview.addItemDecoration(new RecyclerViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, 1, Color.GRAY));
        mBaseQuickAdapter.setEnableLoadMore(true);
        mBaseQuickAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadData();
                ALog.d("current Page is" + startPage);

            }
        });
        mBaseQuickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ArticleData.DatasBean item = mBaseQuickAdapter.getItem(position);
                startActivity(new Intent(getActivity(),Html5Activity.class).putExtra("url",item.getLink()));
            }
        });

        mSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(!mSwiperefreshlayout.isRefreshing()){
                    mBaseQuickAdapter.notifyDataSetChanged();
                    mSwiperefreshlayout.setRefreshing(true);
                }else{
                    mSwiperefreshlayout.setRefreshing(false);
                }
            }
        });



        RetrofitManager.getInstance().getBannersList(new MyBaseListObserver<BaseResponse<List<BannerData>>>() {

            @Override
            protected void onDoSomeThing(BaseResponse<List<BannerData>> listBaseResponse) {
                mBannerData = listBaseResponse.data;
                for (BannerData bannerData : mBannerData) {
                    images.add(bannerData.getImagePath());
                    descs.add(bannerData.getDesc());
                    //   ALog.d(mBannerData.toString());
                }
            }

            @Override
            protected void onFinished() {
                ALog.d("加载完成");
                //设置图片集合
                mBanner.setImages(images);
                //设置标题集合（当banner样式有显示title时）
                mBanner.setBannerTitles(descs);
                //设置banner样式
                mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
                //设置图片加载器
                mBanner.setImageLoader(new GlideImageLoader());
                //设置banner动画效果
                mBanner.setBannerAnimation(Transformer.DepthPage);
                ALog.d("before start");
                //设置自动轮播，默认为true
                mBanner.isAutoPlay(true);
                //设置轮播时间
                mBanner.setDelayTime(1500);
                //设置指示器位置（当banner模式中有指示器时）
                mBanner.setIndicatorGravity(BannerConfig.CENTER);
                //banner设置方法全部调用完毕时最后调用
                mBanner.start();
            }
        });

        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                BannerData bannerData = mBannerData.get(position);
                startActivity(new Intent(getContext(), Html5Activity.class).putExtra("url", bannerData.getUrl()));
            }
        });


        loadData();


    }

    /**
     * 加载数据  应该放在P层
     */
    private void loadData() {
        RetrofitManager.getInstance().getArticleList(startPage, new MyBaseListObserver<BaseResponse<ArticleData>>() {
            @Override
            protected void onDoSomeThing(BaseResponse<ArticleData> articleDataBaseResponse) {
                mArticleData = articleDataBaseResponse.data;
                List<ArticleData.DatasBean> datas = mArticleData.getDatas();
                mBaseQuickAdapter.addData(datas);

            }

            @Override
            protected void onFinished() {
                if (mArticleData.getPageCount() == startPage) {  //判断是否是最后一页
                    //如果是最后一页
                    mBaseQuickAdapter.setEnableLoadMore(false);
                    showMessage("已经是最后一页了哦！");
                    mBaseQuickAdapter.loadMoreEnd();
                } else {
                    mBaseQuickAdapter.loadMoreComplete();
                    startPage += 1;
                }
            }
        });
    }


}
